package com.jvxb.modules.configuration.exception;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jvxb
 * @since 2020-04-13
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @description: 处理由业务抛出的ServiceException异常信息
     */
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public Map<String, Object> handleServiceException(ServiceException e) {
        log.error("平台业务异常记录 " + e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("message", e.getMessage());
        return map;
    }

    /**
     * @description: 处理由断言等抛出的IllegalArgumentException异常信息
     */
    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Map<String, Object> handleArgException(IllegalArgumentException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("data", null);
        map.put("message", e.getMessage());
        return map;
    }

    /**
     * @description: 处理程序未捕获的Exception异常信息
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> handleException(Exception e) {
        log.error("平台通用异常记录 " + e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("data", null);
        map.put("message", e.getMessage());
        return map;
    }

}